<template>
  <div class="exam">
    <el-card style="width:98%;margin:30px auto;">
      <div clas="title" style="font-weight:bold;font-size:17px">考试管理</div>

      <div style="display: flex;justify-content: space-between">
        <div style="margin: 20px 2px">
          <el-button type="primary" icon="el-icon-plus" circle @click="open" title="添加"></el-button>

          <el-button type="danger" @click="deleteBatch" icon="el-icon-delete" title="批量删除" slot="reference"
                     style="margin-left: 10px"></el-button>
        </div>
        <div style="margin: 20px 5px">
          <el-input v-model="name" style="width: 200px" placeholder="请输入考试名称"
                    suffix-icon="el-icon-search"></el-input>
          <el-button class="ml-5" type="primary" style="margin-left: 10px" @click="load">搜索</el-button>
          <el-button type="warning" @click="reset">重置</el-button>
        </div>


      </div>
      <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"
                @selection-change="handleSelectionChange" size="medium"
      >

        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
             <el-table-column prop="id" label="ID" width="50">
             </el-table-column>
        <el-table-column prop="name" label="考试名称">
        </el-table-column>
        <el-table-column prop="classroom" label="考试教室" width="80">
        </el-table-column>
        <el-table-column prop="startTime" :formatter="dateFormat1" label="开始时间">
        </el-table-column>

        <el-table-column prop="endTime" :formatter="dateFormat1" label="结束时间">
        </el-table-column>
        <el-table-column prop="teacher" label="监考老师" width="80">
        </el-table-column>
        <el-table-column prop="druation" label="时长/分" width="80">
        </el-table-column>

        <el-table-column
          prop="corseName"
          label="所属课程"
          align="center"
        >
                    <template v-slot="scope">
                      <!--<span v-if="courses && courses.length">{{courses.find(v=>v.id==scope.row.courseId).name}}</span>-->
                      <div v-for="item in courses ">
                        <span v-if="scope.row.courseId==item.id">{{ item.name }}</span>
                      </div>
                    </template>
        </el-table-column>

        <el-table-column label="设置试卷" width="100">
          <template slot-scope="scope">
            <el-button type="primary" @click="setPaper(scope.row.id)">设置</el-button>
          </template>
        </el-table-column>


        <el-table-column prop="state" label="考试状态" width="80">
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)" icon="el-icon-edit" circle></el-button>

            <!--删除-->
            <el-button @click="delete1(scope.row.id)"
                       slot="reference" type="danger" icon="el-icon-delete" circle
                       style="margin-left: 10px"></el-button>

          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 10px 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>


    <el-dialog
      title="试卷"
      :visible.sync="dialogVisible1"

      :destroy-on-close="true"
    >
      <el-form :model="forms" label-width="120px" size="medium"  ref="forms" class="demo-ruleForm">
      <el-form-item label="试卷名称" prop="paperId">
        <el-select v-model="forms.paperId" placeholder="请选择试卷">
          <el-option v-for="item in papers" :label="item.name" :value="item.id" :key="item.id">

          </el-option>

        </el-select>
      </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1=false">取 消</el-button>
        <el-button type="primary" @click="selectPaper">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="新增考试"
      :visible.sync="dialogVisible"
      :destroy-on-close="true"
    >
      <el-form :model="form" label-width="120px" size="medium" :rules="rules" ref="form" class="demo-ruleForm">
        <el-form-item label="考试名称" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="考试教室" prop="classroom">
          <el-input v-model="form.classroom" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="时长/分钟" prop="druation">
          <el-input v-model="form.druation" autocomplete="off"></el-input>
        </el-form-item>
        <!--
                <el-form-item label="考试时间" prop="time">
                  <el-date-picker
                    v-model="form.time"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>
        -->
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="监考老师" prop="teacher">
          <el-input v-model="form.teacher" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程">
            <el-option v-for="item in courses" :label="item.name" :value="item.id" :key="item.id"></el-option>

          </el-select>
        </el-form-item>
        <!--        <el-form-item label="考试状态" prop="state">-->
        <!--          <el-input v-model="form.state" autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>

    </el-dialog>


  </div>
</template>

<script>
import request from '../../utils/request'

export default {
  name: "Dict",
  data() {
    return {
      forms:{},
      rules: {
        name: [
          {required: true, message: '请输入考试名称', trigger: 'blur'}
          // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        classroom: [
          {required: true, message: '请输入考试教室', trigger: 'blur'},
          // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],

        time: [
          {required: true, message: '请选择考试时间', trigger: 'blur'}
          // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        teacher: [
          {required: true, message: '请输入监考老师', trigger: 'blur'}
          // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ], state: [
          {required: true, message: '请选择考试状态', trigger: 'blur'}
          // {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        courseName: [
          {required: true, message: '请选择课程', trigger: 'blur'}
        ],
        startTime: [
          {required: true, message: '请选择开始时间', trigger: 'blur'}
        ],
        endTime: [
          {required: true, message: '请选择结束时间', trigger: 'blur'}
        ]
      },
      dialogVisible1: false,
      roles: [],
      headerBg: 'headerBg',
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      name: "",
      dialogVisible: false,
      form: {},
      //批量删除
      multipleSelection: [],
      courses: [],
      papers: [],
    }
  },
  created() {
    //请求数据
    this.load()
    this.request.get("/course/findAll").then(res => {
      this.courses = res.data
    })

    this.request.post("/paper/selectAll").then(res => {
      this.papers = res.data
    })


  },
  methods: {

    selectPaper(){

          request.post("/examPaper/save", this.forms).then(res => {
            if (res.code==200) {
              this.$message({
                type: "success",
                message: "保存成功"

              })
              this.dialogVisible1 = false

            } else {
              this.$message({
                type: "error",
                message: "保存失败"
              })
            }
          })

    },

    setPaper(examId) {

      this.forms={examId:examId}
      this.request.get("/examPaper/exam/"+examId).then(res => {
        if(res.data){
          this.forms.paperId=res.data.paperId
        }
        this.dialogVisible1 = true
      })

    },

    dateFormat1(row, column, cellValue, index) {
      const daterc = row[column.property]
      if (daterc != null) {
        var date = new Date(daterc);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      }
    },


    dateFormat(row) {

      const daterc = row
      if (daterc != null) {
        var date = new Date(daterc);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      }
    },

    //消除校验
    resetForm() {
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      })

      this.dialogVisible = false

    },
    deleteBatch() {
      let ids = this.multipleSelection.map(v => v.id)  //将对象数变为纯id数组
      this.$confirm('确定批量删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'msgbox',
        type: 'warning'
      }).then(() => {
        request.post("/exam/del/batch", ids).then(res => {
          if (ids.length === 0) {
            this.$message({
              type: 'warning',
              message: '请选择数据!'
            });
            return
          }
          if (res) {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            });
            this.load()
          } else {
            this.$message({
              type: 'error',
              message: '批量删除失败!'
            });
          }

        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    //删除
    delete1(id) {
      this.$confirm('确定删除此条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'msgbox',
        type: 'warning'
      }).then(() => {
        request.delete("/exam/delete/" + id).then(res => {
          if (res) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.load()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }

        })

      }).catch(() => {
        this.$message({
          type: 'success',
          message: '已取消删除'
        });
      });
    },

    //更新
    edit(row) {
      this.form = row
      this.dialogVisible = true
    },

    //新增
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {  // 表单校验合法
          console.log(this.form.startTime)
         /* this.form.time = this.dateFormat(this.form.time)
          this.form.time = this.dateFormat(this.form.startTime)
          this.form.time = this.dateFormat(this.form.endTime)*/
          if (this.form.startTime > this.form.endTime) {
            this.$message({
              type: 'warning',
              message: '开始时间不能大于结束时间'
            })
            return
          }

          request.post("/exam/save", this.form).then(res => {
            if (res) {
              this.$message({
                type: "success",
                message: "保存成功"

              })
              this.dialogVisible = false
              // sessionStorage.setItem("user", JSON.stringify(this.form))
              this.load()
            } else {
              this.$message({
                type: "error",
                message: "保存失败"
              })
            }
          })
        }
      })
    },
    //新增弹窗
    open() {
      this.dialogVisible = true
      this.form = {}
    },
    //重置
    reset() {
      this.name = "",
        this.load()
    },

    //分页
    load() {
      request.get("/exam/findPage", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,

        }
      }).then(res => {
        this.tableData = res.data.page
        this.total = res.data.count
      })

      /* fetch("http://localhost:9091/user/page?pageNum="+this.pageNum+"&pageSize="+this.pageSize+"&username="+this.username+"&nickname="+this.nickname).then(res => res.json()).then(res => {
           console.log(res)
           this.tableData = res.data
           this.total = res.total
       })*/
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()

    },
    handleCurrentChange(val) {
      this.pageNum = val

      this.load()
    }
  }
}
</script>

<style lang="scss" scope>
.exam{

  .headerBg {
    background: #eee !important;
  }
  .el-dialog {
    width: 40%;
  }


  @media screen and (max-width: 440px) {
    .el-dialog {
      width: 90%;
    }
  }

  @media only screen and (min-width:600px) and (max-width:1200px){
    .el-dialog {
      width: 60%;
    }
  }

  @media only screen and (min-width:440px) and (max-width:599px){
    .el-dialog {
      width: 80%;
    }
  }
}

</style>
<style >

@media (max-width: 720px) {
  .msgbox{
    width: 327px !important;
  }
}

</style>
